package com.hanyxx.thread.lock;

import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo04 {
    public static void main(String[] args) throws InterruptedException {
        Demo04Service service = new Demo04Service();
        Demo04ThreadA threadA = new Demo04ThreadA(service);
        //A进入等待状态
        threadA.start();
        Demo04ThreadB threadB = new Demo04ThreadB(service);
        //B进入等待状态
        threadB.start();
        Thread.sleep(3000L);
        //只唤醒A
        service.signal_A();
    }
}
class Demo04Service{
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    //等待方法A
    public void awaitA() throws InterruptedException {
        lock.lock();
        System.out.println("awaitA方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        conditionA.await();
        System.out.println("awaitA方法结束于：" + sdf.format(new Date(System.currentTimeMillis())));
        lock.unlock();
    }
    //等待方法B
    public void awaitB() throws InterruptedException {
        lock.lock();
        System.out.println("awaitB方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        conditionB.await();
        System.out.println("awaitB方法结束于：" + sdf.format(new Date(System.currentTimeMillis())));
        lock.unlock();
    }
    //通知方法A
    public void signal_A() {
        lock.lock();
        System.out.println("signal_A方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        //唤醒A
        conditionA.signal();
        lock.unlock();
    }
    //通知方法B
    public void signal_B() {
        lock.lock();
        System.out.println("signal_B方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        //唤醒B
        conditionB.signal();
        lock.unlock();
    }
}
class Demo04ThreadA extends  Thread{
    private Demo04Service service;
    public Demo04ThreadA(Demo04Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.awaitA();
    }
}
class Demo04ThreadB extends  Thread{
    private Demo04Service service;
    public Demo04ThreadB(Demo04Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.awaitB();
    }
}

